import { useAction } from '@/hooks'
import {
  editUserInfoAction,
  editUserPhotoAction,
  getEditInfoAction,
} from '@/store/modules/user'
import { history } from '@/utils/history'
import {
  Button,
  DatePicker,
  Dialog,
  List,
  NavBar,
  Popup,
  Toast,
} from 'antd-mobile'
import classNames from 'classnames'
import styles from './index.module.scss'
// 导入修改 昵称 的组件
import { AppDispatch } from '@/store'
import { logOutAction } from '@/store/actions/login'
import { formatTime } from '@/utils/auth'
import { getError } from '@/utils/Error'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import EditInput from './EditInput/index'
import EditList from './EditList'
import { useEditName, useEditSel } from './service'
export type InputPopup = {
  type: '' | 'name' | 'intro'
  value: string
  visible: boolean
}
export type selPopup = {
  type: '' | 'gender' | 'photo'
  visible: boolean
}
const Item = List.Item
const type: Record<number, string> = {
  0: '男',
  1: '女',
}
const ProfileEdit = () => {
  // 二次解构赋值 获取编辑数据
  const {
    editInfo: { photo, name, intro, gender, birthday },
  } = useAction(getEditInfoAction, 'user')
  const dispatch = useDispatch<AppDispatch>()
  // 使用自定义hook抽出逻辑
  const { inputShow, openPopup, closePopup } = useEditName()
  //
  // 控制修改性别头像弹层显隐的
  const { selShow, openSelPopup, closeSelPopup } = useEditSel()
  // 控制 birth 显隐
  const [birthShow, setBirthShow] = useState(false)
  //父组件获取最新数据
  const updateName = async (
    value: string | FormData,
    type: string,
    onclose: () => void
  ) => {
    // console.log('修改头像传过来', { [type]: value })
    try {
      // 根据传过来的type作为参数对象的键，value作为值
      if (type === 'photo' && typeof value !== 'string') {
        await dispatch(editUserPhotoAction(value))
      } else {
        await dispatch(editUserInfoAction({ [type]: value }))
      }
      Toast.show({
        icon: 'success',
        content: '修改成功',
        position: 'top',
      })
      onclose()
    } catch (error) {
      getError(error)
    }
  }
  const logout = () => {
    // Dialog.confirm({
    //   content: '是否退出登录',
    //   onConfirm: async () => {
    //     await dispatch(logOutAction())
    //     Toast.show({
    //       icon: 'success',
    //       content: '退出登录成功',
    //       position: 'bottom',
    //     })
    //     history.push('/login')
    //   },
    // })
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            },
          },
          {
            key: 'confirm',
            text: '退出',
            style: {
              color: 'var(--adm-color-weak)',
            },
            onClick: async () => {
              await dispatch(logOutAction())
              history.push('/login')
              handler.close()
            },
          },
        ],
      ],
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.back()}>
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={
                      photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                    }
                    alt=""
                  />
                </span>
              }
              arrow
              onClick={() => openSelPopup('photo')}>
              头像
            </Item>

            <Item arrow extra={name} onClick={() => openPopup('name', name)}>
              昵称
            </Item>
            <Item
              arrow
              onClick={() => openPopup('intro', intro || '')}
              extra={
                <span className={classNames('intro', 'normal')}>
                  {intro || '未填写'}
                </span>
              }>
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item
              arrow
              extra={type[+gender]}
              onClick={() => openSelPopup('gender')}>
              性别
            </Item>
            <Item
              arrow
              extra={birthday}
              onClick={() => {
                setBirthShow(true)
              }}>
              生日
            </Item>
          </List>
          {/* 日期弹层 */}
          {/* 修改生日 日期选择器 */}
          <DatePicker
            // 默认不可见
            mouseWheel={true}
            visible={birthShow}
            value={new Date()}
            title="选择年月日"
            min={new Date(1900, 0, 1, 0, 0, 0)}
            max={new Date()}
            precision="day"
            onConfirm={(val) => {
              updateName(formatTime(val), 'birthday', () => setBirthShow(false))
            }}
          />
        </div>
        <div className="logout">
          <Button className="btn" onClick={logout}>
            退出登录
          </Button>
        </div>
      </div>
      {/* 修改昵称弹层 */}
      <Popup
        visible={inputShow.visible}
        position="left"
        bodyStyle={{ height: '40vh' }}>
        {/* 弹层内容 修改昵称和简介*/}
        <EditInput
          close={closePopup}
          data={inputShow}
          onUpdateName={updateName}
        />
      </Popup>
      {/* 修改性别和头像 */}
      <Popup
        visible={selShow.visible}
        position="bottom"
        onMaskClick={closeSelPopup}>
        {/* 弹层内容 */}
        <EditList
          close={closeSelPopup}
          onUpdateName={updateName}
          type={selShow.type}
        />
      </Popup>
    </div>
  )
}

export default ProfileEdit
